package com.project.template.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.template.common.Result;
import com.project.template.dto.LoginDTO;
import com.project.template.dto.UserDTO;
import com.project.template.entity.User;
import com.project.template.enums.StatusType;
import com.project.template.exception.CustomException;
import com.project.template.mapper.UserMapper;
import com.project.template.service.UserService;

import com.project.template.utils.JwtUtils;
import com.project.template.vo.UserVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

private UserMapper userMapper;

    private UserVO UserVO;

    @Override
    public boolean save(User entity) {
        check(entity);
        entity.setCreateTime(LocalDateTime.now());
        entity.encryptedPassword(entity.getPassword());
        return super.save(entity);
    }

    @Override
    public boolean updateById(User entity) {
        check(entity);
        User entityOld = getById(entity.getId());
        entity.setPassword(entityOld.getPassword());
        return super.updateById(entity);
    }

    private void check(User entity) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, entity.getUsername());
        wrapper.ne(entity.getId() != null, User::getId, entity.getId());
        if (exists(wrapper)) {
            throw new CustomException("用户名已存在");
        }
    }

    @Override
    public boolean removeByIds(Collection<?> list) {
        List<Integer> integerList = (List<Integer>) list;
        return super.removeByIds(integerList);
    }

    @Override
    public Result login(String username, String password) {
        // 查询用户是否存在
        // 查询用户是否存在
        User user = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getPassword, password));

        if (user == null) {
            return  new Result<>().error("用户名或密码错误");
        }


        // 登录成功，返回用户信息（根据需要返回部分信息）
        return  new Result<>().success(user);
    }

    @Override
    public Page<User> page(Map<String, Object> query, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(User::getId);
        if (ObjectUtils.isNotEmpty(query.get("username"))) {
            wrapper.like(User::getUsername, query.get("username"));
        }
        if (ObjectUtils.isNotEmpty(query.get("phone"))) {
            wrapper.like(User::getUsername, query.get("phone"));
        }

        if (ObjectUtils.isNotEmpty(query.get("sex"))) {
            wrapper.eq(User::sex, query.get("sex"));
        }

        return page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public void changePassword(Integer userId, String oldPassword, String newPassword) {
        User user = this.getById(userId);
        if (user == null) {
            throw new CustomException("用户不存在");
        }

        // 检查旧密码是否正确
        if (!user.getPassword().equals(oldPassword)) {
            throw new CustomException("旧密码不正确");
        }

        // 更新新密码
        user.setPassword(newPassword);
        boolean result = this.updateById(user);
        if (!result) {
            throw new CustomException("密码更新失败");
        }
        System.out.println("Password updated successfully for user: " + userId);
        this.updateById(user);
    }



    @Override
    public UserVO login(LoginDTO loginDTO) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, loginDTO.getUsername());
        User user = getOne(wrapper);

        if (user == null) {
            throw new CustomException("请检查用户名密码是否正确");
        }
        // 密码加密
        // String password = SecureUtil.md5(userLoginDTO.getPassword() + sysUser.getSalt());
        String password = loginDTO.getPassword();
        if (!user.getPassword().equals(password)) {
            throw new CustomException("请检查用户名密码是否正确");
        }

        //检查用户状态是否被禁用
        if (StatusType.DISABLED.equals(user.getStatus())) {
            throw new CustomException("当前用户已经被禁用");
        }

        //生成jwt
        String token = JwtUtils.generateToken(user);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        userVO.setToken(token);
        //生成菜单
        return userVO;
    }

    @Override
    public void register(UserDTO userDTO) {
        User entity = new User();
        entity.setUsername(userDTO.getUsername());
        entity.setPassword(userDTO.getPassword());
        //账号默认为启用
        save(entity);
    }




}
